package cn.faifai.desktop.view.components.treeDirectory;

import cn.faifai.desktop.api.TagController;
import cn.faifai.desktop.events.TagNodeIsSelectedEvent;
import cn.faifai.desktop.events.TagTreeItemSecondaryClickEvent;
import cn.faifai.framework.utils.SingleEvenBus;
import cn.faifai.common.utils.SpringContextUtil;
import cn.faifai.desktop.utils.VirtualThreadPoolManager;
import cn.faifai.desktop.view.components.menus.TagTreeItemMenu;
import cn.faifai.tagapi.entity.Tag;
import com.google.common.eventbus.EventBus;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class TagBrowser extends VBox {
    private TreeView<TagItem> treeView;
    private EventBus eventBus;
    @Autowired
    private TagController tagController;

    public TagBrowser initUI() {
        eventBus = SingleEvenBus.getInstance();
        TreeItem<TagItem> root = new TreeItem<>(new TagItem("标签云", 0l));
        treeView = new TreeView(root);

        // 设置双击监听器
        treeView.setOnMouseClicked(event -> {
            if (event.getClickCount() == 2) { // 检查是否是双击
                log.info("双击事件");
                TreeItem<TagItem> selectedItem = treeView.getSelectionModel().getSelectedItem();
                loadChildren(selectedItem);
            }
            if (event.getClickCount() == 1){
                log.info("单击事件");
                if (event.getButton() == MouseButton.PRIMARY){
                    log.info("开始添加选中事件");
                    TreeItem<TagItem> selectedItem = treeView.getSelectionModel().getSelectedItem();
                    eventBus.post(new TagNodeIsSelectedEvent(selectedItem.getValue().getId()));
                    log.info("添加选中事件成功");
                    TagTreeItemMenu.getMenu().hide();
                }
                if(event.getButton() == MouseButton.SECONDARY){
                    log.info("右键事件");
                    TreeItem<TagItem> selectedItem = treeView.getSelectionModel().getSelectedItem();
                    if (selectedItem != null){
                        TagTreeItemMenu.getMenu().hide();
                        TagTreeItemMenu.getMenu().show(treeView, event.getScreenX(), event.getScreenY());
                        eventBus.post(new TagTreeItemSecondaryClickEvent(selectedItem.getValue().getId(), selectedItem.getValue().getName(), selectedItem));
                    }
                }
            }
        });

        treeView.setMaxWidth(Double.MAX_VALUE);  // 允许横向无限扩展
        treeView.setMaxHeight(Double.MAX_VALUE); // 允许纵向无限扩展

        VBox.setVgrow(treeView, Priority.ALWAYS); // 给树组件分配扩展优先权

        // 添加到布局
        this.getChildren().add(treeView);
        return this;
    }

    public void loadChildren(TreeItem<TagItem> parentItem) {
        log.info("加载标签子节点");
        Task<List<TagItem>> loadTask = new Task<>() {
            @Override
            protected List<TagItem> call() {
                List<Tag> oneLayerList = tagController.getOneLayerListByParentId(parentItem.getValue().id);
                List<TagItem> tagItems = oneLayerList.stream().map(item -> new TagItem(item.getName(), item.getId())).toList();
                return tagItems;
            }
        };

        loadTask.setOnSucceeded(e -> {
            List<TagItem> children = loadTask.getValue();
            parentItem.getChildren().clear();
            parentItem.getChildren().addAll(
                    children.stream()
                            .map(item -> new TreeItem<>(item))
                            .toList()
            );
            parentItem.setExpanded(true);
            parentItem.getChildren().stream().forEach(item -> {
                if (SpringContextUtil.getContext().getBean(TagController.class).hasChild(item.getValue().id)){
                    item.getChildren().add(new TreeItem<>());
                }
            });
        });
        VirtualThreadPoolManager.getInstance().submit(loadTask::run);
    }

    /**
     *  搜索节点
     */
    public TreeItem<TagItem> searchNonRecursive(Long searchId) {
        if (treeView == null) return null;

        // 使用栈来存储待检查的节点
        java.util.LinkedList<TreeItem<TagItem>> queue = new java.util.LinkedList<>();
        queue.push(treeView.getRoot());

        while (!queue.isEmpty()) {
            TreeItem<TagItem> currentNode = queue.poll();

            // 检查当前节点是否匹配
            if (currentNode.getValue().getId().equals(searchId)) {
                return currentNode;
            }

            // 将当前节点的所有子节点压入栈中
            ObservableList<TreeItem<TagItem>> children = currentNode.getChildren();
            for (int i = children.size() - 1; i >= 0; i--) { // 注意：逆序添加以保持原始顺序
                if (children.get(i).getValue() == null) continue;// 检查有子节点的时候会加一个空节点实现懒加载，此时不在目录中造成搜索的空指针异常
                queue.push(children.get(i));
            }
        }

        // 如果没有找到匹配的节点，则返回null
        return null;
    }


    // 定义数据模型
    @Getter
    public static class TagItem {
        private final String name;
        private final Long id;

        public TagItem(String name, Long id) {
            this.name = name;
            this.id = id;
        }

        @Override
        public String toString() {
            return name;
        }
    }
}
